<template>
  <div class="container" v-if="enabledDebugger">
    <view
      id="menu"
      class="dev-icon"
      ref="myMenu"
      :style="{ transform: `translate(${drag.x || 0}px, ${drag.y || 0}px)` }"
      @touchstart="(e) => drag.start(e)"
      @touchmove.stop.prevent="(e) => drag.move(e)"
      @touchend="(e) => drag.end(e)"
      @click="showPopup = !showPopup"
    >
      D
    </view>

    <devtool-popup v-model="showPopup">
      <div class="uni-devtool__wrapper">
        <DebuggerBox :isFromWindow="true" />
      </div>
    </devtool-popup>
  </div>
</template>
<script>
import { ElDrag } from './utils/drag.js'
import DevtoolPopup from './components/devtoolPopup'
import DebuggerBox from './components/debuggerBox.vue'
import { installDebugger } from './utils/debuggerExtern'

export default {
  name: 'uni-devtool',
  components: {
    DevtoolPopup,
    DebuggerBox
  },
  data() {
    return {
      showPopup: false,
      drag: {},
      enabledDebugger: false
    }
  },
  computed: {
    getDebugEnabled() {
      return getApp().globalData
    },
    isDeBugger() {
      return false
    }
  },
  watch: {
    isDeBugger: {
      handler () {
        if (this.isDeBugger) {
          this.init()
        } else {
          this.destroyDeBugger()
        }
      },
      immediate: true
    }
  },
  methods: {
    init() {
      installDebugger({
        enableRequestInterceptor: true,
        showGlobalFloatWindow: true
      })
      this.enabledDebugger = true
      setTimeout(() => {
        const query = uni.createSelectorQuery().in(this)
        const menuRef = query.select('#menu')
        this.drag = new ElDrag(menuRef)
      }, 500)
    },
    destroyDeBugger() {
      this.enabledDebugger = false
    }
  },
  destroyed() {
    if (this.drag && this.drag.destroy) {
      this.drag.destroy()
    }
  }
}
</script>
<style scoped>
.dev-icon {
  position: fixed;
  bottom: 100rpx;
  right: 5px;
  z-index: 9999;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  background: rgba(0, 0, 0, 0.3);
  user-select: none;
}
.uni-devtool__wrapper {
  display: flex;
  flex-direction: column;
  color: #000;
  font-size: 14px;
  height: 100%;
  overflow: hidden;
}

.menus {
  white-space: nowrap;
  overflow-x: scroll;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #e4e7ed;
}
.meun-item {
  display: inline-block;
  height: 35px;
  line-height: 35px;
  padding: 0 10px;
  border-right: 1px solid #e4e7ed;
  list-style: none;
  background: #f5f7fa;
}
.meun-item.actived {
  background: #fff;
}
.main__container {
  flex: 1;
  overflow: hidden;
}
</style>
